package com.wno704.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.wno704.quartz.service.JobService;
import com.wno704.system.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("test")
public class TestController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private JobService jobService;

	@ResponseBody
	@GetMapping("/test/{jdbcTemplateDstName}/{jdbcTemplateDstName}")
	public String getTest(@PathVariable("jdbcTemplateDstName") String jdbcTemplateSrcName, @PathVariable("jdbcTemplateDstName") String jdbcTemplateDstName) {

		JdbcTemplate jdbcTemplateSrc = (JdbcTemplate)SpringContextUtil.getBean(jdbcTemplateSrcName);
		JdbcTemplate jdbcTemplateDst = (JdbcTemplate)SpringContextUtil.getBean(jdbcTemplateDstName);

		System.out.println(jdbcTemplateSrc.getDataSource());
		System.out.println(jdbcTemplateDst.getDataSource());


		String sql = "SELECT count(1) FROM QRTZ_JOB_LOG T";

		System.out.println("######################"+jdbcTemplateDst.queryForObject(sql, Integer.class));

		return null;
	}

	@ResponseBody
	@GetMapping("/runJob/{jobIds}")
	public String runJob(@PathVariable("jobIds") String jobIds) {
		jobService.run(jobIds);
		return null;
	}

	@ResponseBody
	@GetMapping("/runGet")
	public String runGet(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		String str = getRequestParam(request);
		return str;
	}

	@ResponseBody
	@PostMapping("/runPost")
	public String runPost(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		String str = getRequestParam(request);
		return str;
	}

	@ResponseBody
	@PostMapping("/runPostJson")
	public String runPostJson(HttpServletRequest request, @RequestBody JSONObject jsonObject, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		String msg =  jsonObject.toJSONString();
		return msg;
	}

	private String getRequestParam(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = request.getReader();
			String line;
			while ((line = reader.readLine()) != null) {
				if (line.length() > 1) {
					sb.append(line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}

}
